<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 功能权限类
 * @package  htdocs
 * @author   allen.qiang
 * @version 1.0
 */

class permission {

    /**
     * 新增或修改权限
     * @param array $arg_array 权限参数数组
     * @return array
     */
    public function editPermission( $arg_array ) {

        global $G_SHOP;

        if (!isset($arg_array['uuid'], $arg_array['permissionID'], $arg_array['permissionName'], $arg_array['permissionGroupID'], $arg_array['permissionRequest'], $arg_array['operator'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }


        if (!quanli_is_int( $arg_array['permissionID'] )) {
            return array( 'code' => 400, 'message' => '请输入权限号' );
        }

        if (empty($arg_array['permissionName'])) {
            return array( 'code' => 400, 'message' => '请输入权限名称' );
        }

        if ($arg_array['permissionGroupID'] == 0) {
            return array( 'code' => 400, 'message' => '请选择权限组' );
        } else if ($arg_array['permissionGroupID'] == -1 && empty($arg_array['newGroup'])) {
            return array( 'code' => 400, 'message' => '请输入新权限组名称' );
        }

        if (empty($arg_array['permissionRequest'])) {
            return array( 'code' => 400, 'message' => '请输入权限路径' );
        }

        //获得权限数组
        $permission_group_array = $this->searchPermissionGroup();

        try {

            $permission_obj = new entity('user_permission');
            if (empty($arg_array['uuid'])) { //新增

                //查询权限ID是否已存在
                $p_arg_array = array(
                    'permissionID' => $arg_array['permissionID']
                );
                $permission_array = $this->searchPermission( $p_arg_array );
                if ($permission_array) {
                    throw new Exception('权限号已存在', 404);
                }

                //查询权限名称是否已存在
                $p_arg_array = array(
                    'permissionName' => $arg_array['permissionName']
                );
                $permission_array = $this->searchPermission( $p_arg_array );
                if ($permission_array) {
                    throw new Exception('权限名称已存在', 404);
                }

                //检查权限组
                if ($arg_array['permissionGroupID'] == -1) { //新建权限组

                    if ($permission_group_array) {
                        foreach($permission_group_array as &$group) {
                            if ($group['permissionGroupName'] == $arg_array['newGroup']) {
                                throw new Exception('权限组名称已存在', 404);
                            }
                            $permission_obj->permissionGroupID = $group['permissionGroupID'];
                        }
                        $permission_obj->permissionGroupID += 1;
                    } else {
                        $permission_obj->permissionGroupID = 1;
                    }
                    $permission_obj->permissionGroupName = $arg_array['newGroup'];

                } else { //已有权限组

                    $permission_obj->permissionGroupID = $arg_array['permissionGroupID'];
                    if (!isset($permission_group_array[$permission_obj->permissionGroupID])) {
                        throw new Exception('选择的权限组信息不存在', 404);
                    }
                    $permission_obj->permissionGroupName = $permission_group_array[$permission_obj->permissionGroupID]['permissionGroupName'];

                }

                unset($permission_group_array);

            } else { //修改

                //查询权限信息
                $permission_obj->uuid = $arg_array['uuid'];
                if (!$G_SHOP->DBCA->fetch($permission_obj)) {
                    throw new Exception('权限信息没有找到', 404);
                }

                if ($permission_obj->permissionID != $arg_array['permissionID']) {

                    //查询权限ID是否已存在
                    $p_arg_array = array(
                        'permissionID' => $arg_array['permissionID']
                    );
                    $permission_array = $this->searchPermission( $p_arg_array );
                    if ($permission_array) {
                        throw new Exception('权限号已存在', 404);
                    }

                }

                if ($permission_obj->permissionName != $arg_array['permissionName']) {

                    //查询权限名称是否已存在
                    $p_arg_array = array(
                        'permissionName' => $arg_array['permissionName']
                    );
                    $permission_array = $this->searchPermission( $p_arg_array );
                    if ($permission_array) {
                        throw new Exception('权限名称已存在', 404);
                    }

                }

                if ($arg_array['permissionGroupID'] != $permission_obj->permissionGroupID) {

                    //检查权限组
                    if ($arg_array['permissionGroupID'] == -1) { //新建权限组

                        if ($permission_group_array) {
                            foreach($permission_group_array as &$group) {
                                if ($group['permissionGroupName'] == $arg_array['newGroup']) {
                                    throw new Exception('权限组名称已存在', 404);
                                }
                                $permission_obj->permissionGroupID = $group['permissionGroupID'];
                            }
                            $permission_obj->permissionGroupID += 1;
                        } else {
                            $permission_obj->permissionGroupID = 1;
                        }
                        $permission_obj->permissionGroupName = $arg_array['newGroup'];

                    } else { //已有权限组

                        $permission_obj->permissionGroupID = $arg_array['permissionGroupID'];
                        if (!isset($permission_group_array[$permission_obj->permissionGroupID])) {
                            throw new Exception('选择的权限组信息不存在', 404);
                        }
                        $permission_obj->permissionGroupName = $permission_group_array[$permission_obj->permissionGroupID]['permissionGroupName'];

                    }

                    unset($permission_group_array);

                }


            }
            $permission_obj->permissionID = $arg_array['permissionID'];
            $permission_obj->permissionName = $arg_array['permissionName'];
            $permission_obj->permissionRequest = $arg_array['permissionRequest'];
            $G_SHOP->DBCA->save( $permission_obj );

            return array( 'code' => 200, 'message' => '权限保存成功' );

        } catch( Exception $e ) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 查询权限信息
     * @param $arg_array
     * @param array $arg_array
     * )
     * @return array|null
     */
    public function searchPermission( &$arg_array ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //参数转换
        if(!empty($arg_array['s_permissionGroupID']) && quanli_is_int($arg_array['s_permissionGroupID'])){
            $arg_array['permissionGroupID'] = $arg_array['s_permissionGroupID'];
        }

        //权限ID
        if (isset($arg_array['permissionID']) && quanli_is_int($arg_array['permissionID'])) {
            $sql .= ' AND permissionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['permissionID'];
        }

        //权限名称
        if (isset($arg_array['permissionName']) && !empty($arg_array['permissionName'])) {
            $sql .= ' AND permissionName = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['permissionName'];
        }

        //权限组ID
        if (isset($arg_array['permissionGroupID']) && is_numeric($arg_array['permissionGroupID'])) {
            $sql .= ' AND permissionGroupID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['permissionGroupID'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM user_permission' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM user_permission' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array) {
                return null;
            }

            foreach ($temp_item_array as &$item) {

                $item_array[] = array(
                    'uuid' => $item->uuid,
                    'permissionID' => $item->permissionID,
                    'permissionName' => $item->permissionName,
                    'permissionRequest' => $item->permissionRequest,
                    'permissionGroupID' => $item->permissionGroupID,
                    'permissionGroupName' => $item->permissionGroupName
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 查询权限组信息
     * @return mixed
     */
    public function searchPermissionGroup() {

        global $G_SHOP;

        $sql = 'SELECT permissionGroupID,permissionGroupName FROM user_permission GROUP BY permissionGroupID ORDER BY permissionGroupID ASC';

        $temp_item_array = $G_SHOP->DBCA->stmt_query($sql);

        if (!$temp_item_array) {
            return null;
        }

        foreach($temp_item_array as &$item) {
            $item_array[$item->permissionGroupID] = array(
                'permissionGroupID' => $item->permissionGroupID,
                'permissionGroupName' => $item->permissionGroupName
            );
        }

        return $item_array;

    }

    /**
     * 删除权限
     * @param array $permission_array 权限ID数组
     * @return array
     */
    public function deletePermission( $permission_array ) {

        global $G_SHOP;

        if (!isset($permission_array) || !is_array($permission_array) || empty($permission_array)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            foreach ($permission_array as &$permissionID) {

                if (!is_numeric($permissionID) || $permissionID <= 0) {
                    continue;
                }

                $delete_sql = 'DELETE FROM user_permission WHERE permissionID = ?';
                $G_SHOP->DBCA->stmt_query($delete_sql, 'i', $permissionID);

            }

            return array( 'code' => 200, 'message' => '权限删除成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

}